//
//  WFGuideViewController.m
//  谷居
//
//  Created by dllo on 16/6/16.
//  Copyright © 2016年 刘万方. All rights reserved.
//

#import "WFGuideViewController.h"
#import "WFNavigationView.h"
#import "WFLabel.h"
#import "WFTableView.h"
#import "WFGuideCell.h"

#import "AFNetworking.h"
#import "WFHandleURL.h"
#import "WFGuideModel.h"
#import "WFBannerModel.h"


#import "YJPCycleView.h"

#import "MJRefresh.h"

#import "WFHandleURL.h"
#import "WFGuideDetailVC.h"
@interface WFGuideViewController ()<UITableViewDataSource, UITableViewDelegate, YJPCycleViewDelegate, WFNavigationViewDelegate>
@property (nonatomic, retain) WFNavigationView *navigationView;

@property (nonatomic, retain) UIImageView *hairlineImageViewUnder;



@property (nonatomic, retain) WFLabel *titleLabel; /** 标题label. */

@property (nonatomic, retain) WFTableView *guideTableView; /** 主界面的TableView. */

@property (nonatomic, retain) NSMutableArray *guideArray; /** 用来存储GuiderModel的数组. */

@property (nonatomic, retain) NSMutableArray *carouselArray; /** 轮播图的数组. */

/** 网络数据的参数*/

@property (nonatomic, assign) NSInteger userId;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, assign) NSInteger start;

@property (nonatomic, assign) NSString *orderString;

@property (nonatomic, assign) NSInteger cateGory;
@end

@implementation WFGuideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
#pragma mark - 数组没有retain
    
    
    
    /** 设置bartintcolor. */
    [self createNavigationView];
    
    /** 创建tableView. */
    [self createTableView];
    
//    /** 创建FreeDesign按钮. */
//    [self createFreeDesignButton];
//    
    /** 网络请求. */
    NSString *url = [WFHandleURL guideHandleURLWithUserId:self.userId count:self.count start:self.start orderString:self.orderString cateGory:self.cateGory];
    
    [self makeRequestWithURL:url upDown:YES];

}


#pragma mark - 创建刷新

- (void)refresh {
    self.start = 0;
    NSLog(@"refres执行");
    self.orderString = @"CATEGORY";
    NSString *url = [WFHandleURL guideHandleURLWithUserId:self.userId count:self.count start:self.start orderString:self.orderString cateGory:self.cateGory];
    NSLog(@"%@", url);
    [self makeRequestWithURL:url upDown:YES];
    [_guideTableView.mj_header endRefreshing];
}

- (void)loadMore {
    self.start += 10;
    NSString *url = [WFHandleURL guideHandleURLWithUserId:self.userId count:self.count start:self.start orderString:self.orderString cateGory:self.cateGory];;
    [self makeRequestWithURL:url upDown:NO];
    [_guideTableView.mj_footer endRefreshing];
}


#pragma mark - 懒加载
- (NSInteger)userId {
    if (!_userId) {
        _userId = 0;
    }
    return _userId;
}

- (NSInteger)count {
    if (!_count) {
        _count = 10;
    }
    return _count;
}

- (NSInteger)start {
    if (!_start) {
        _start = 0;
    }
    return _start;
}

- (NSMutableArray *)guideArray {
    if (_guideArray == nil) {
        _guideArray = [[NSMutableArray array]retain];
    }
    return _guideArray;
}

- (NSMutableArray *)carouselArray {
    if (_carouselArray == nil) {
        _carouselArray = [[NSMutableArray array] retain];
    }
    return _carouselArray;
}
#warning 不确定懒加载是否正确
- (NSString *)orderString {
    if (!_orderString) {
        _orderString = [[NSString string] retain];
    }
    return [_orderString autorelease];
}


- (NSInteger)cateGory {
    if (!_cateGory) {
        _cateGory = 0;
    }
    return _cateGory;
}


#pragma mark - 创建导航栏
- (void)createNavigationView {
    _navigationView = [[WFNavigationView alloc] initWithFrame:NA_FRAME];
    [self.view addSubview:_navigationView];
    [_navigationView release];
    _navigationView.backgroundColor = [UIColor yellowColor];
    _navigationView.buttonCount = 3;
    _navigationView.navigationType = 2;
    _navigationView.delegate = self;
    _hairlineImageViewUnder = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    /** 创建titleLabel. */
    [self createTitleLabel];
//    [self.view bringSubviewToFront:_navigationView];
    
}


- (void)backTorefreshTableViewWithId:(NSString *)_id indexType:(NSInteger)type {
    self.cateGory = _id.integerValue;
    [self refresh];
    NSLog(@"iddddd: %ld, %@", type, _id);
}

#pragma mrak - 删除导航栏下滑线
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0 ) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
    
}


- (void)createTitleLabel {
    _titleLabel = [[WFLabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    self.navigationItem.titleView = _titleLabel;
//    _titleLabel.backgroundColor = [UIColor whiteColor];
    _titleLabel.text = @"装修攻略";
    _titleLabel.textAlignment = 1;
}



#pragma mark - 创建TableView
- (void)createTableView {
    _guideTableView = [[WFTableView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 48 - 84) style:UITableViewStylePlain];
    [self.view addSubview:_guideTableView];
    [_guideTableView release];
    _guideTableView.rowHeight = 130;
    _guideTableView.delegate = self;
    _guideTableView.dataSource = self;
    
//    [_guideTableView registerClass:[WFGuideCell class] forCellReuseIdentifier:@"guide"];
    
    [_guideTableView registerClass:[WFGuideCell class] forCellReuseIdentifier:NSStringFromClass([WFGuideCell class])];
    
    _guideTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    _guideTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.guideArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WFGuideCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WFGuideCell class]) forIndexPath:indexPath];
    cell.guideModel = self.guideArray[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WFGuideDetailVC *vc = [[WFGuideDetailVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
    WFGuideModel *model = self.guideArray[indexPath.row];
    vc.URL = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/strategy/strategy/%ld", model.id];
}

/** ************************ */

#pragma mark - 网络请求

- (void)makeRequestWithURL:(NSString *)url upDown:(BOOL)upDown {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *stageListArray = responseObject[@"strategyList"];
        
        
        if (upDown) {
            [self.guideArray removeAllObjects];
            self.guideArray = [WFGuideModel baseModelByArray:stageListArray];
        } else {
            NSMutableArray *arr = [WFGuideModel baseModelByArray:stageListArray];
            [self.guideArray addObjectsFromArray:arr];
        }
        [_guideTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
#pragma mark - 创建轮播图
    NSString *bannerUrl = @"http://api.guju.com.cn/v2/strategy/banner";
    [manager GET:bannerUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *bannerArray = responseObject[@"banners"];
        self.carouselArray = [WFBannerModel baseModelByArray:bannerArray];
        
        
        YJPCycleView *carouselView = [[YJPCycleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200) DataSource:self.carouselArray TimeInterval:1 cachesData:nil];
        _guideTableView.tableHeaderView = carouselView;
        carouselView.delegate = self;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
}

/** 轮播图的点击方法. */
- (void)didClickedItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"轮播图被点击.");
}
- (void)viewDidAppear:(BOOL)animated {
    NSLog(@"攻略显示. ");
    /** 设置全局变量. */
    SYMBOL = @3;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"symbolChange" object:nil];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _hairlineImageViewUnder.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [super viewDidAppear:animated];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
//    [_guideArray release];
    [super dealloc];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
